package com.atguigu.gulimall.seckill.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author : Jungle
 * @Description :
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    public static final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    public static final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码（用id直接扣不安全）

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1、扫描最近三天需要参数秒杀的活动
        R session = couponFeignService.getLatest3DaysSession();
        if (session.getCode() == 0) {
            //   上架商品信息
            List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //    缓存到redis
            //    1、缓存活动信息
            saveSessionInfos(sessionData);
            //    2、缓存活动的关联商品信息

            saveSessionSkuInfos(sessionData);

        }

    }




    public List<SeckillSkuRedisTo> blockHandler(BlockException ex){
        log.error("getCurrentSeckillSkusResource被限流了==>{}",ex);
        return null;
    }

    /**
     * 返回当前时间可以参与秒杀的商品信息
     *
     * 这里自定义了一段资源  try-with-resource
     * blockHandler 函数会在原方法被限流/降级/系统保护的时候调用，
     * 而 fallback 函数会针对所有类型的异常
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource",blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1、确定当前时间属于哪个场次
        //距离1970差值
        long currTime = System.currentTimeMillis();
        //获取所有的场次信息
        try (Entry entry= SphU.entry("seckillSkus")){
            Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
            for (String key : keys) {
                //seckill:sessions:1660752000000_1660759200000
                String[] s = key.replace(SESSION_CACHE_PREFIX, "").split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if (currTime >= start && currTime <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    // promotion_session_id_skuId  3-9  3-11
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redis = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            //redis.setRandomCode(null);   当前秒杀开始就需要随机码
                            return redis;
                        }).collect(Collectors.toList());
                        //返回商品信息集合
                        return collect;
                    }
                    break;
                }

            }
        } catch (BlockException e) {
          log.error("资源被限流==>{}",e.getMessage());
        }

        //2、获取整个秒杀场次所需要的所有商品信息
        return null;
    }

    /**
     * 1、从redis中获取到当前秒杀的商品信息
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                //6_4
                //正则匹配  \\d代表数字
                if (Pattern.matches(regx, key)) {
                    String s = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                    //过滤出来当前场次的2_9  3_9  或者过期的
                    //随机码只是在秒杀时间才返回
                    if (System.currentTimeMillis() >= redisTo.getStartTime() && System.currentTimeMillis() <= redisTo.getEndTime()) {
                        return redisTo;
                    } else {
                        redisTo.setRandomCode(null);
                        return redisTo;
                    }

                }

            }
        }
        return null;
    }

    // TODO: 2022/8/20  上架秒杀商品的时候，每一个数据都有过期时间
    // TODO: 2022/8/20  秒杀后续的流程，简化了，收货信息
    @Override
    public String kill(String killId, String key, Integer num) {
        Instant now1 = Instant.now();
        MemberRespVo respVo = LoginUserInterceptor.threadLocal.get();
        //1、获取当前商品秒杀信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            //1、校验时间合法性
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            Long ttl = endTime - startTime;
            long currTime = System.currentTimeMillis();
            if (currTime >= startTime && currTime <= endTime) {
                //2、校验随机码和商品id是否正确
                String randomCode = redis.getRandomCode();
                String session_sku = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && session_sku.equals(killId)) {
                    //3、验证购物数量是否合理
                    if (num.intValue() <= redis.getSeckillLimit().intValue()) {
                        //4、验证这个人是否已经买过了，幂等性;如果秒杀成功就去占位 userId_PromotionSessionId_skuId
                        String redisKey = respVo.getId() + "_" + session_sku;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，说明从来没买过
                            // 获取分布式信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //100毫秒的最大 等待时间，不成功就返回false  计算耗时 最大120ms  平均20ms
                            //boolean b = semaphore.tryAcquire(num,100,TimeUnit.MILLISECONDS);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //    秒杀成功
                                //   快速下单 ，发送MQ 10ms
                                String orderSn = IdWorker.getTimeId();
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(orderSn)
                                        .setPromotionSessionId(redis.getPromotionSessionId())
                                        .setSkuId(redis.getSkuId())
                                        .setSeckillPrice(redis.getSeckillPrice())
                                        .setNum(num)
                                        .setMemberId(respVo.getId())
                                ;

                                //String exchange, String routingKey, Object message
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                Instant now2 = Instant.now();
                             log.info("秒杀订单耗时==>{}",Duration.between(now1,now2).toMillis());
                                return orderSn;
                            }

                        } else {
                            //说明买过了
                            return null;
                        }
                    }
                }
            }
        }
        return null;

    }

    /**
     * 活动信息保存用list
     * K: seckill:sessions:startTime_endTime      v:
     */
    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        if (sessions != null) {
            sessions.stream().forEach(session -> {
                //  开始时间和结束时间转成long类型
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                //设置key   seckill:sessions:startTime_endTime
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                Long ttl = endTime - startTime;
                //做幂等性处理
                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    //缓存活动信息
                    //seckill:sessions:startTime_endTime   value list<skuId>
                    redisTemplate.opsForList().leftPushAll(key, collect);
                    redisTemplate.expire(key, ttl, TimeUnit.MILLISECONDS);
                }
            });
        }

    }

    /**
     * 保存商品用hash结构
     * <seckill:skus,<id,SeckillSkuVo>>
     */
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {

        if (sessions != null) {
            sessions.stream().forEach(session -> {
                //准备hash操作
                //<seckill:skus,<skuId,redisTo>>
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    String token = IdUtil.fastSimpleUUID();
                    String skuKey = seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString();
                    if (!ops.hasKey(skuKey)) {
                        //缓存商品
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        //1、sku的基本数据
                        R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(info);
                        }

                        //2、sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3、设置上当前商品的秒杀时间
                        long startTime = session.getStartTime().getTime();
                        long endTime = session.getEndTime().getTime();
                        redisTo.setStartTime(startTime);
                        redisTo.setEndTime(endTime);

                        //4、随机码  防刷  seckill?skuId=1&key=ddfdfs
                        redisTo.setRandomCode(token);
                        String string = JSON.toJSONString(redisTo);
                        long ttl = endTime - startTime;
                        ops.expire(ttl, TimeUnit.MILLISECONDS);
                        ops.put(skuKey, string);

                        //上架商品，同时上架信号量，保证幂等
                        //如果当前这个场次的商品库存信息已经上架就不需要上架
                        //5、使用库存作为分布式信号量  --限流
                        //设置分布式信号量的名字 seckill:stock:token  每次都不一样，防刷
                        String semaphoreKey = SKU_STOCK_SEMAPHORE + token;
                        //这里主要是放置多节点机器，重置信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(semaphoreKey);
                        semaphore.expire(ttl, TimeUnit.MILLISECONDS);
                        //商品可以秒杀的数量作为信号量
                        boolean b = semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                        if (b){
                        // 锁定商品库存
                        //    这里省略

                        }
                    }
                });
            });
        }
    }
}
